package com.tdu.spider.biz.service.same;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.google.common.base.Joiner;
import com.google.common.collect.Lists;
import com.tdu.spider.biz.cont.UserTypeCont;
import com.tdu.spider.biz.service.common.UserService;
import com.tdu.spider.biz.service.same.vo.*;
import com.tdu.spider.biz.util.HttpUtils;
import com.tdu.spider.biz.util.ImageUtil;
import com.tdu.spider.model.SameChannelDO;
import com.tdu.spider.model.UserDO;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.fluent.Executor;
import org.apache.http.client.fluent.Request;
import org.apache.http.client.fluent.Response;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.Args;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Random;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.tdu.spider.biz.util.LogUtils.curtail;

@Service
public class SameApiService {

    private static Logger logger = LoggerFactory.getLogger(SameApiService.class);
    @Autowired
    private UserService        userService;
    @Autowired
    private SameChannelService sameChannelService;

    private static List<Header> headers = Lists.newArrayList();

    static {
        headers.add(new BasicHeader("Host", "v2.same.com"));
        headers.add(new BasicHeader("Machine", "android|301|android5.3|XT1089|d:d:d:9958172218|1080|1776"));
        headers.add(new BasicHeader("encode_type", "json"));
        headers.add(new BasicHeader("Accept", "application/json"));
        headers.add(new BasicHeader("Accept-Language", "zh-Hans-CN;q=1"));
        headers.add(new BasicHeader("timezone", "Asia/Shanghai"));
        headers.add(new BasicHeader("User-Agent", "same/540"));
        headers.add(new BasicHeader("Advertising-UUID", "d:d:d:9958172218"));
        headers.add(new BasicHeader("Extrainfo", "ali"));
        headers.add(new BasicHeader("X-same-Client-Version", "540"));
        headers.add(new BasicHeader("X-same-Device-UUID", "d:d:d:9958172218"));
    }


    public List<RecommendationResultVO> recommendationChannel(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.165/recommendation?last_fetch=" + DateTime.now().toDate().getTime();

        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("recommendationChannel url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<List<RecommendationResultVO>> result = JSON.parseObject(content, new TypeReference<CommonResult<List<RecommendationResultVO>>>() {
            });
            List<RecommendationResultVO> resultData = result.getData();
            return resultData;
        }
        return null;
    }


    public List<UserVO> users() throws Exception {
        List<UserDO> userDOList = userService.findByType(UserTypeCont.SAME_USER_TYPE);
        List<UserVO> userVOList = Lists.newArrayList();
        for (UserDO userDO : userDOList) {
            UserVO userVO1 = new UserVO();
            userVO1.setAuth_token(userDO.getToken());
            userVO1.setId(Long.valueOf(userDO.getUserId()));
            userVO1.setUsername(userDO.getName());
            userVOList.add(userVO1);
        }
        return userVOList;
    }

    /**
     * 登录
     *
     * @param userLoginVO
     * @return
     */
    public UserVO login(UserLoginVO userLoginVO) throws Exception {
        List<NameValuePair> forms = Lists.newArrayList();
        forms.add(new BasicNameValuePair("device", userLoginVO.getDevice()));
        forms.add(new BasicNameValuePair("format", "json"));
        forms.add(new BasicNameValuePair("push_token", "mi-uid"));
        forms.add(new BasicNameValuePair("password", userLoginVO.getPassword()));
        forms.add(new BasicNameValuePair("mobile", "+86-" + userLoginVO.getMobile()));

        String url = "https://115.159.131.165/user/login";
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(Request.Post(url).setHeaders(headers.toArray(new Header[]{})).body(new UrlEncodedFormEntity(forms, "UTF-8")).addHeader("X-Same-Request-ID", UUID.randomUUID().toString()));
        String content = response.returnContent().asString();
        logger.info("login url:{},params:{},result:{}", url, userLoginVO, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<UserResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<UserResultVO>>() {
            });
            if (result.getCode() == 0) {
                return result.getData().getUser();
            }
        }
        return null;
    }

    /**
     * 删除帖子(需要登录)
     *
     * @param senceId
     */

    public boolean destorySense(Long senceId) throws Exception {
        String url = "https://115.159.131.165/sense/" + senceId + "/destroy";
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(Request.Get("https://115.159.131.165/sense/" + senceId + "/destroy").setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString()));
        String content = response.returnContent().asString();
        logger.info("destorySense url:{},params:{},result:{}", url, senceId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<Object> result = JSON.parseObject(content, new TypeReference<CommonResult<Object>>() {
            });
            if (result.getCode() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 回复帖子(需要登录)
     *
     * @param message
     */
    public SendMessageVO sendPmsg(SendMessageVO message) throws Exception {
        Args.notNull(message.getBody(), "body");
        Args.notBlank(message.getCmd(), "cmd");
        Args.notBlank(message.getBody().getMsg(), "body.msg");

        StringEntity entity = new StringEntity(JSON.toJSONString(message), "utf-8");
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        String url = "https://115.159.131.24/imuser/sendPmsg";
        Request request = Request.Post(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString()).body(entity);
        setAuth(request, message.getBody().getFuid());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("sendPmsg url:{},params:{},result:{}", url, message, curtail(content));

        if (StringUtils.hasLength(content)) {
            SameImResult<SendMessageVO> result = JSON.parseObject(content, new TypeReference<SameImResult<SendMessageVO>>() {
            });
            if (result.getCode() == 0) {
                return result.getRecv();
            }
        }
        return null;
    }

    /**
     * 查询聊天历史记录
     *
     * @param userChatHistoryVO
     * @return
     * @throws Exception
     */
    public List<UserChatHistoryVO> privateHistory(UserChatHistoryQueryVO userChatHistoryVO) throws Exception {
        Args.notNull(userChatHistoryVO.getUserId(), "userId");
        Args.notNull(userChatHistoryVO.getToUserId(), "toUserId");

        StringBuilder url = new StringBuilder("https://115.159.131.24/immsg/privateHistory");
        url.append("?").append("limit=").append(userChatHistoryVO.getLimit());
        url.append("&").append("uid=").append(userChatHistoryVO.getUserId());
        url.append("&").append("tid=").append(userChatHistoryVO.getToUserId() + "_" + userChatHistoryVO.getUserId());

        Request request = Request.Get(url.toString()).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, userChatHistoryVO.getUserId());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("privateHistory url:{},params:{},result:{}", url, userChatHistoryVO, curtail(content));

        if (StringUtils.hasLength(content)) {
            DataResultVO<UserChatHistoryResultVO> result = JSON.parseObject(content, new TypeReference<DataResultVO<UserChatHistoryResultVO>>() {
            });
            if (result.getCode() == 0) {
                return result.getData().getResults();
            }
        }
        return null;
    }

    /**
     * 喜欢帖子(需要登录)
     *
     * @param query
     */
    public boolean likeSense(UserInfoQuery query) throws Exception {
        Args.notNull(query.getUserId(), "userId");
        Args.notNull(query.getSenseId(), "senseId");
        if (query.getChannelId()!=null && Lists.newArrayList(1403224L, 590L, 1056740L, 1244040L).contains(query.getChannelId())) {
            query.setSenseIds(Lists.newArrayList(query.getSenseId()));
            viewSense(query);
            return true;
        }

        String url = "https://115.159.131.165/sense/" + query.getSenseId() + "/like/create";
        Request request = Request.Post(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("likeSense url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<Object> result = JSON.parseObject(content, new TypeReference<CommonResult<Object>>() {
            });
            return result.getCode() == 0 ? true : false;
        }
        return false;
    }

    /**
     * 喜欢帖子(需要登录)
     *
     * @param querys
     */
    public boolean likeSense(List<UserInfoQuery> querys) throws Exception {
        for (UserInfoQuery query : querys) {
            TimeUnit.MILLISECONDS.sleep(50);
            likeSense(query);
        }
        return false;
    }

    /**
     * 查询渠道详情
     *
     * @param query
     * @return
     * @throws Exception
     */
    public SameChannelDO queryChannelDetail(UserInfoQuery query) throws Exception {
        Args.notNull(query.getChannelId(), "channelId");
        Args.notNull(query.getUserId(), "userId");
        //step2:查询
        String url = "https://115.159.131.165/channel/" + query.getChannelId() + "/detail";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryChannelDetail url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<SameChannelDO> result = JSON.parseObject(content, new TypeReference<CommonResult<SameChannelDO>>() {
            });
            return result.getData();
        }
        return null;
    }

    /**
     * 分页根据渠道ID获取下动态文章(不需要登录)
     * -1 为今日最热
     * -7 为一周最热
     *
     * @param query
     */
    public PageSenseVO pageQueryActivitySense(UserInfoQuery query) throws Exception {
        Args.notBlank(query.getUrl(), "url");

        String url = "https://115.159.131.165" + query.getUrl();
        if (url.contains("default_url")) {
            return pageQueryChannelSense(query);
        }
        url = url.replaceAll("\\{channel_id\\}", query.getChannelId() + "")
                .replaceAll("\\\\", "")
                .replaceAll(" ","%20");
        if (query.getOffset() != null && query.getOffset() > 0) {
            if (url.contains("?")) {
                url += "&offset=" + query.getOffset();
            } else {
                url += "?offset=" + query.getOffset();
            }
        }
        URL url1=new URL(url);
        Request request = Request.Get(url1.toString()).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("pageQueryActivitySense url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<PageSenseVO> result = JSON.parseObject(content, new TypeReference<CommonResult<PageSenseVO>>() {
            });
            PageSenseVO resultData = result.getData();
            if (resultData == null || CollectionUtils.isEmpty(resultData.getResults())) {
                return resultData;
            }
            for (SenSeVO seVO : resultData.getResults()) {
                photoProcess(seVO);
            }
            String offsetStr = resultData.getNext();
            if (StringUtils.hasLength(offsetStr) && offsetStr.contains("offset")) {
                resultData.setOffset(Long.valueOf(offsetStr.substring(offsetStr.lastIndexOf("=") + 1)));
            }
            return resultData;
        }
        return null;
    }

    private void photoProcess(SenSeVO seVO) {
        if (StringUtils.hasLength(seVO.getPhoto()) && seVO.getPhoto().contains("__")) {
            String temp = seVO.getPhoto().substring(seVO.getPhoto().lastIndexOf("__") + 2);
            String[] whs = temp.substring(0, temp.lastIndexOf(".")).replaceAll("w|h|W|H", "").split("_");
            if (whs.length > 1) {
                seVO.setHeight(Integer.valueOf(whs[1]));
                seVO.setWidth(Integer.valueOf(whs[0]));
            } else {
                seVO.setHeight(1080);
                seVO.setWidth(1080);
                logger.error("photoProcess senseId:{},phtot:{}", seVO.getId(), seVO.getPhoto());
            }
        } else if (StringUtils.hasLength(seVO.getPhoto()) && seVO.getPhoto().contains("/screen")) {
            String temp = seVO.getPhoto().substring(seVO.getPhoto().lastIndexOf("screen") + 6);
            String[] whs = temp.substring(0, temp.lastIndexOf(".")).replaceAll("w|h|W|H", "").split("x");
            if (whs.length > 1) {
                seVO.setHeight(Integer.valueOf(whs[1]));
                seVO.setWidth(Integer.valueOf(whs[0]));
            } else {
                seVO.setHeight(1080);
                seVO.setWidth(1080);
                logger.error("photoProcess senseId:{},phtot:{}", seVO.getId(), seVO.getPhoto());
            }
        }
    }


    /**
     * 发表文件，上传文件
     *
     * @param uploadFileVO
     * @return
     * @throws Exception
     */
    public UploadFileResult uploadFile(UploadFileVO uploadFileVO) throws Exception {
        File file = new File(uploadFileVO.getFileName());
        if (!file.exists() || !file.isFile()) {
            return null;
        }
        File newFile = new File(file.getParentFile().getPath() + "/u" + file.getName());
        ImageUtil.zipWidthHeightImageFile(file, newFile, 1080, 824);

        BufferedImage sourceImg = ImageIO.read(new FileInputStream(newFile));
        String uuid = UUID.randomUUID().toString().toUpperCase();
        if (sourceImg.getWidth() > sourceImg.getHeight()) {

        }
        String key = uuid + "__c0_-256_" + sourceImg.getWidth() + "_" + sourceImg.getWidth() + "__w" + sourceImg.getWidth() + "_h" + sourceImg.getHeight() + ".jpg";
        key = UUID.randomUUID().toString() + "__c0_-128_1080_1080__w1080_h824.jpg";
        logger.warn("out {}", key);
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        ContentType contentType = ContentType.create(ContentType.MULTIPART_FORM_DATA.getMimeType(), Charset.defaultCharset());
        builder.setCharset(Charset.defaultCharset());
        builder.addTextBody("token", uploadFileVO.getToken(), contentType);
        builder.addTextBody("key", "image/" + key, contentType);
        builder.addBinaryBody("file", file, ContentType.APPLICATION_OCTET_STREAM, key);
        HttpEntity httpEntity = builder.build();

        Request request = Request.Post("http://upload.qiniu.com").addHeader("User-Agent", "QiniuObject-C/7.1.5 (android5.3; CF2542E9-3742-43F9-9F5D-4D9DE411CEDD; jibUmSMRoHWog8QNM0f__B8J1lhFDMWl7pGBmNUS)").addHeader("Connection", "Keep-Alive").addHeader("Accept-Encoding", "gzip,deflate").addHeader("Accept-Language", "zh-cn").addHeader("Accept", "*/*").addHeader("Host", "upload.qiniu.com").body(httpEntity);
        String content = request.execute().returnContent().asString();
        logger.info("uploadFile params:{},entity:{},result:{}", uploadFileVO, builder, content);

        if (StringUtils.hasLength(content)) {
            UploadFileResult result = JSON.parseObject(content, UploadFileResult.class);
            return result;
        }
        return null;
    }


    public UploadFileResult batchCreateSense(List<AddSenSeVO> senSeVOS) throws Exception {
        List<AddSenSeVO> addSenSeVOS = Lists.newArrayList();
        for (AddSenSeVO seVO : senSeVOS) {
            Response response = Request.Get(seVO.getFileUrl()).userAgent("").execute();
            InputStream inputStream = response.returnContent().asStream();
        }

        return null;
    }


    public UploadTokenResult getUploadTokenByUserId(Long userId) throws Exception {
        String url = "https://115.159.131.165/qiniu/token";
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString()));
        String content = response.returnContent().asString();
        logger.info("getUploadTokenByUserId url:{},params:{},result:{}", userId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<UploadTokenResult> result = JSON.parseObject(content, new TypeReference<CommonResult<UploadTokenResult>>() {
            });
            if (result.getCode() == 0) {
                return result.getData();
            }
        }
        return null;
    }

    /**
     * 发表文字文章
     *
     * @param addSenSeVO
     * @return
     * @throws Exception
     */
    public SenSeVO createSense(AddSenSeVO addSenSeVO) throws Exception {
        if (addSenSeVO == null || !StringUtils.hasLength(addSenSeVO.getText())) {
            return null;
        }
        if (addSenSeVO.getUserId() == null) {
            return null;
        }
        String contxt = addSenSeVO.getText();// URLEncoder.encode(addSenSeVO.getText(),"UTF-8");
        int randomInt = new Random().nextInt(99999999);
        Executor executor = Executor.newInstance(HttpUtils.httpClient());
        //组装参数
        List<NameValuePair> forms = Lists.newArrayList();
        forms.add(new BasicNameValuePair("channel_id", String.valueOf(addSenSeVO.getChannelId())));
        forms.add(new BasicNameValuePair("media_id", ""));
        if (StringUtils.hasLength(addSenSeVO.getFileUrl())) {
            forms.add(new BasicNameValuePair("src", addSenSeVO.getFileUrl()));
        }
        forms.add(new BasicNameValuePair("r", String.valueOf(randomInt)));
        forms.add(new BasicNameValuePair("txt", contxt));

        String url = "https://115.159.131.165/sense/create?r=" + randomInt;
        Request request = Request.Post(url).setHeaders(headers.toArray(new Header[]{})).addHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8").body(new UrlEncodedFormEntity(forms, "UTF-8"));
        setAuth(request, addSenSeVO.getUserId());
        Response response = executor.execute(request);
        String content = response.returnContent().asString();
        logger.info("createSense url:{},txt:{},params:{},result:{}", url, contxt, addSenSeVO, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<SenSeVO> result = JSON.parseObject(content, new TypeReference<CommonResult<SenSeVO>>() {
            });
            if (result.getCode() == 0) {
                SenSeVO senSeVO = result.getData();
                photoProcess(senSeVO);
                return senSeVO;
            }
        }
        return null;
    }

    public void setAuth(Request request, Long userId) {
        UserDO userDO = userService.get(UserTypeCont.SAME_USER_TYPE + "-" + String.valueOf(userId));
        String token = String.format("Token %s", userDO.getToken());
        //logger.info("setAuth {}", token);
        request.addHeader("Authorization", token);
    }

    /**
     * 获取用户所有渠道(需要登录)
     *
     * @param query
     * @return
     * @throws Exception
     */

    public List<SameChannelDO> channels(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.165/user/" + query.getUserId() + "/channels?channels=all&contacts=recent&kv=yes";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("channels url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<ChannelSubscribeVO> result = JSON.parseObject(content, new TypeReference<CommonResult<ChannelSubscribeVO>>() {
            });
            if (result.getCode() == 0) {
                List<ChannelInfoVO> subscribe_channels = result.getData().getSubscribe_channels();
                List<SameChannelDO> data = Lists.newArrayList();
                if (!CollectionUtils.isEmpty(subscribe_channels)) {
                    for (ChannelInfoVO subscribe_channel : subscribe_channels) {
                        data.addAll(subscribe_channel.getChannel());
                    }
                }
                return data;
            }
        }
        return Lists.newArrayList();
    }

    /**
     * 分页根据渠道获取下文章(不需要登录)
     *
     * @param query
     * @return
     */

    public PageSenseVO pageQueryChannelSense(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.165/channel/" + query.getChannelId() + "/senses";

        return query(url, query);
    }


    private PageSenseVO query(String url, UserInfoQuery query) throws Exception {
        if (query.getOffset() != null && query.getOffset() > 0) {
            url = url + "?offset=" + query.getOffset();
        }
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        if (query.getUserId() != null) {
            setAuth(request, query.getUserId());
        }
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("pageQuerySense url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<PageSenseVO> result = JSON.parseObject(content, new TypeReference<CommonResult<PageSenseVO>>() {
            });
            if (result.getCode() == 0) {
                PageSenseVO resultData = result.getData();
                if (resultData == null || CollectionUtils.isEmpty(resultData.getResults())) {
                    return resultData;
                }
                for (SenSeVO seVO : resultData.getResults()) {
                    photoProcess(seVO);
                }
                if (!CollectionUtils.isEmpty(resultData.getResults())) {
                    resultData.setOffset(resultData.getResults().get(resultData.getResults().size() - 1).getId());
                }
                return resultData;
            }
        }
        return null;
    }

    /**
     * 分页根据用户查询文章(不需要登录)
     *
     * @param query
     * @return
     */
    public PageSenseVO pageQueryUserSense(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.165/user/" + query.getUserId() + "/senses";
        if (query.getOffset() != null && query.getOffset() > 0) {
            url = url + "?offset=" + query.getOffset();
        }
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("pageQueryChannelSense url:{},params:{},result:{}", url, query, curtail(content));

        if (!StringUtils.hasLength(content)) {
            return null;
        }
        CommonResult<PageSenseVO> result = JSON.parseObject(content, new TypeReference<CommonResult<PageSenseVO>>() {
        });
        if (result.getCode() == 0) {
            PageSenseVO resultData = result.getData();
            if (resultData == null || CollectionUtils.isEmpty(resultData.getResults())) {
                return resultData;
            }
            for (SenSeVO seVO : resultData.getResults()) {
                photoProcess(seVO);
            }
            if (StringUtils.hasLength(resultData.getNext()) && resultData.getNext().contains("offset")) {
                resultData.setOffset(Long.valueOf(resultData.getNext().substring(resultData.getNext().lastIndexOf("=") + 1)));
            } else {
                //如果没数据，则返回
                resultData.setOffset(-1L);
                return resultData;
            }
            return resultData;
        }
        return null;
    }

    /**
     * 根据文章ID获取文章详情(不需要登录)
     *
     * @param query
     * @return
     */
    public SenSeVO querySenseDetail(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.165/sense/" + query.getSenseId();
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString()));
        String content = response.returnContent().asString();
        logger.info("querySenseDetail url:{},params:{},result:{}", url, query, curtail(content));

        if (!StringUtils.hasLength(content)) {
            return null;
        }
        CommonResult<SenSeVO> result = JSON.parseObject(content, new TypeReference<CommonResult<SenSeVO>>() {
        });
        if (result.getCode() == 0) {
            SenSeVO senSeVO = result.getData();
            photoProcess(senSeVO);
            return senSeVO;
        }
        return null;
    }

    /**
     * 浏览文章(需要登录)
     *
     * @param query
     * @return
     */
    public boolean viewSense(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.165/sense/view";
        Request request = Request.Post(url).setHeaders(headers.toArray(new Header[]{}));
        request.bodyForm(new BasicNameValuePair("ids", Joiner.on(",").join(query.getSenseIds())));
        request.addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("viewSense url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<SenSeVO> result = JSON.parseObject(content, new TypeReference<CommonResult<SenSeVO>>() {
            });
            if (result.getCode() == 0) {
                return true;
            }
        }
        return false;
    }

    /**
     * 查询未读消息（不知）
     *
     * @param query
     * @throws Exception
     */
    public void queryUnreadMessage(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.24/imcatalog/unread_catalog_mids";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{}));
        request.addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryUnreadMessage url:{},params:{},result:{}", url, query, (content));

        if (StringUtils.hasLength(content)) {
            DataResultVO<Object> result = JSON.parseObject(content, new TypeReference<DataResultVO<Object>>() {
            });
            if (result.getCode() == 0) {
            }
        }
    }

    /**
     * 查询用户未读消息
     *
     * @param query
     * @return
     * @throws Exception
     */
    public UserMessageResultVO queryMessage(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.24/imcatalog/list?limit=30&uid=" + query.getUserId();
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{}));
        request.addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, query.getUserId());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryMessage url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            DataResultVO<UserMessageResultVO> result = JSON.parseObject(content, new TypeReference<DataResultVO<UserMessageResultVO>>() {
            });
            if (result.getCode() == 0) {
                return result.getData();
            }
        }
        return null;
    }


    public UserBoboResultVO queryBoboRank(UserInfoQuery query) throws Exception {
        String url = "https://115.159.131.165/relationship/bobo-rank";
        if (query.getUserId() != null) {
            url += "?user_id=" + query.getUserId();
        }
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{}));
        request.addHeader("X-Same-Request-ID", UUID.randomUUID().toString());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryBoboRank url:{},params:{},result:{}", url, query, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<UserBoboResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<UserBoboResultVO>>() {
            });
            if (result.getCode() == 0) {
                return result.getData();
            }
        }
        return null;
    }


    /**
     * 查询当前渠道活跃度
     *
     * @param channelId
     * @return
     * @throws Exception
     */
    public Integer queryChannelCount(Long channelId) throws Exception {
        String url = "https://115.159.131.165/imchannel/oluserscount?channel_id=" + channelId;
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString()).addHeader("Authorization", "Token 1512264669-qvFSAgidFmAjuTMY-15111234"));
        String content = response.returnContent().asString();
        logger.info("queryChannelCount url:{},params:{},result:{}", channelId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<CountVO> result = JSON.parseObject(content, new TypeReference<CommonResult<CountVO>>() {
            });
            if (result.getCode() == 0) {
                return result.getData().getCount();
            }
        }
        return 0;
    }

    /**
     * 查询用户余额
     *
     * @param userId
     * @return
     * @throws Exception
     */

    public Integer queryAccountBalance(Long userId) throws Exception {
        String url = "https://payment.ohsame.com/app/account.php?action=getBalance";
        List<Header> _headers = SameApiService.headers.subList(1, SameApiService.headers.size());
        Request request = Request.Get(url).setHeaders(_headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, userId);
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryAccountBalance url:{},params:{},result:{}", url, userId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<BalanceResult> result = JSON.parseObject(content, new TypeReference<CommonResult<BalanceResult>>() {
            });
            if (result.getCode() == 0) {
                return result.getData().getBalance();
            }
        }
        return null;
    }

    /**
     * 自动提现用户余额
     *
     * @param userId
     * @throws Exception
     */
    public OrderResultVO drawCash(Long userId) throws Exception {
        //查询余额
        Integer balance = queryAccountBalance(userId);
        if(balance<100){
            logger.error("{}收款失败,余额不足{}",userId,balance);
            return null;
        }
        String url = "https://payment.ohsame.com/app/draw_cash.php";
        List<BasicNameValuePair> pairs = Lists.newArrayList();
        pairs.add(new BasicNameValuePair("amount", balance+""));
        pairs.add(new BasicNameValuePair("card_id", "0"));
        pairs.add(new BasicNameValuePair("type", "3"));

        List<Header> _headers = SameApiService.headers.subList(1, SameApiService.headers.size());
        Request request = Request.Post(url).setHeaders(_headers.toArray(new Header[]{}));
        request.bodyForm(pairs);
        request.addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, userId);

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("drawCash url:{},params:{},result:{}", url, userId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<OrderResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<OrderResultVO>>() {
            });
            if (result.getCode() == 0) {
                return result.getData();
            }
        }
        return null;
    }

    /**
     * 根据文章ID获取喜欢的人
     *
     * @param senseId
     * @return
     * @throws Exception
     */

    public List<SenseLikeVO> querySenseLikeUsers(Long senseId) throws Exception {
        String url = "https://115.159.131.165/sense/" + senseId + "/likers";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, 15814301L);
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("querySenseLikeUsers url:{},params:{},result:{}", url, senseId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<SenseLikeResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<SenseLikeResultVO>>() {
            });
            if (result.getCode() == 0 && result.getData() != null) {
                return result.getData().getResults();
            }
        }
        return Lists.newArrayList();
    }

    /**
     * 根据文章ID获取浏览的人
     *
     * @param senseId
     * @return
     * @throws Exception
     */

    public List<SenseLikeVO> querySenseViewUsers(Long senseId) throws Exception {
        String url = "https://115.159.131.165/sense/" + senseId + "/viewers?limit=60";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, 15814301L);
        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("querySenseViewUsers url:{},params:{},result:{}", url, senseId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<SenseLikeResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<SenseLikeResultVO>>() {
            });
            if (result.getCode() == 0 && result.getData() != null) {
                return result.getData().getResults();
            }
        }
        return Lists.newArrayList();
    }

    /**
     * 查询用户信息
     *
     * @param userId
     * @return
     * @throws Exception
     */

    public UserVO queryUserDetail(Long userId) throws Exception {
        String url = "https://115.159.131.165/user/" + userId + "/profile";
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());
        setAuth(request, 15814301L);

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryUserDetail url:{},params:{},result:{}", url, userId, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<UserResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<UserResultVO>>() {
            });
            if (result.getCode() == 0 && result.getData() != null) {
                return result.getData().getUser();
            }
        }
        return null;
    }

    /**
     * 搜索频道
     * @param txt
     * @return
     * @throws Exception
     */
    public List<SameChannelDO> querySearchChannel(String txt) throws Exception {
        String url = "https://115.159.131.165/channel/search?query=" + URLEncoder.encode(txt,"UTF-8");
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("querySearchChannel url:{},params:{},result:{}", url, txt, curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<ChannelResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<ChannelResultVO>>() {
            });
            if (result.getCode() == 0 && result.getData() != null) {
                return result.getData().getResults();
            }
        }
        return null;
    }

    /**
     * 查询火热的渠道
     * @return
     * @throws Exception
     */
    public List<SameChannelDO> queryHotChannel() throws Exception {
        String url = "https://115.159.131.165/config/recommended_search" ;
        Request request = Request.Get(url).setHeaders(headers.toArray(new Header[]{})).addHeader("X-Same-Request-ID", UUID.randomUUID().toString());

        Response response = Executor.newInstance(HttpUtils.httpClient()).execute(request);
        String content = response.returnContent().asString();
        logger.info("queryHotChannel url:{},params:{},result:{}", url, "", curtail(content));

        if (StringUtils.hasLength(content)) {
            CommonResult<HotChannelResultVO> result = JSON.parseObject(content, new TypeReference<CommonResult<HotChannelResultVO>>() {
            });
            if (result.getCode() == 0 && result.getData() != null && result.getData().getValue()!=null) {
                return result.getData().getValue().getChannels();
            }
        }
        return null;
    }


}
